import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {Form, Table, Modal, Button, Tooltip, Input, message} from 'antd';

import {defaultPagination, TableBtn} from "../publicComponents";
import {config, mUrl} from "../../../config";
import moment from "moment";
import {post, get} from '../../../utils';
import utils from "../../../utils/utils";
import PicturesWall from "../../../compoments/PictureWall";
import {PlusOutlined, ReloadOutlined} from '@ant-design/icons';

const Page = () => {
    const [form] = Form.useForm();
    const [dataSource, setDataSource] = useState([]); // 表格数据
    const [visible, setVisible] = useState(false);
    const [detailModalVisible, setDetailModalVisible] = useState(false);
    const [detail, setDetail] = useState({});
    const [pagination, setPagination] = useState(Object.assign({},defaultPagination)); // 表格分页
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 90,
            render: (text, record, index) => ((pagination.pageSize * (pagination.current ? pagination.current - 1 : 0)) + index + 1)
        },
        {
            title: '操作',
            align: 'center',
            width: 180,
            render: (text, record, index) => {
                return (
                    <TableBtn
                        record={record}
                        onClick={handleTableBtnClick}
                        btns={[
                            {id: 1, name: '详情'},
                            {id: 2, name: '修改'},
                            {id: 3, name: record.noticestate === 1 ? '停用' : '启用'},
                            {id: 4, name: '删除'},
                        ]}
                    />
                );
            }
        },
        {
            title: '状态',
            dataIndex: 'noticestate',
            align: 'center',
            width: 80,
            render: isable => {
                const text = isable === 1 ? '有效' : '已停用';
                const color = isable === 1 ? '#000' : 'red';
                return <span style={{color}}>{text}</span>;
            }
        },
        {
            title: '标题',
            dataIndex: 'headline',
            width: 200,
            align: 'center',
        },
        {
            title: '内容',
            dataIndex: 'noticecontent',
            align: 'center',
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 15 ? text.substr(0, 15) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '创建人',
            dataIndex: 'createuser',
            width: 120,
            align: 'center',
        },
        {
            title: '创建时间',
            dataIndex: 'createtime',
            align: 'center',
            width: 120,
            render: create_time => utils.getDate(create_time)
        },
    ];

    useEffect(() => {
        fetch();
    }, []);

    const fetch = async (params = {}) => {
        let start = 1;
        if (params.startList > 1) {
            start = params.startList;
        }
        get(mUrl.searchMessNoticeList, {pageNo: start, pageSize: pagination.pageSize, ...params}).then((res) => {
            const {list = [], count = 0} = res.data;
            pagination.total = count;
            setPagination(pagination);
            setDataSource(list);
        });
    };

    const handleTableBtnClick = (id, record) => {
        if (id === 1) { // 点击修改
            setDetail(record);
            setTimeout(() => {
                setDetailModalVisible(true);
            }, 500);
        } else if (id === 2) { // 点击修改
            setDetail(record);
            setTimeout(() => {
                setVisible(true);
            }, 500);
        } else if (id === 3 || id === 4) { // 点击停用/删除
            let text = '删除';
            let noticestate = -2;
            if (id === 3) {
                noticestate = record.noticestate === 1 ? -1 : 1;
                text = record.noticestate === 1 ? '停用' : '启用';
            }
            Modal.confirm({
                title: '提示',
                content: <span>是否确定将公告<span style={{color: 'red'}}>{record.headline}</span>{text}？</span>,
                onOk: async () => {
                    handleUpdate(record.noticeid, noticestate, text);
                }
            });
        }
    };

    const handleUpdate = async (noticeid, noticestate, text) => {
        get(mUrl.udMessNotice, {noticeid, noticestate}).then((res) => {
            if (res.state === 1) {
                message.success(text + '成功');
                fetch();
            }
        });
    };

    const handleTableChange = (page) => {
        pagination.current = page.current;
        pagination.pageSize = page.pageSize;
        setPagination(pagination);
        fetch({
            startList: pagination.current,
        });
    };

    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>基础设置 / 公告管理</p></label>
            <div style={{marginBottom: 10}}>
                <Button
                    onClick={() => {
                        setDetail({});
                        setVisible(true);
                    }}
                    type={'primary'}>
                    <PlusOutlined/>新增公告
                </Button>
                <Button
                    type='primary'
                    style={{ marginLeft: 5}}
                    onClick={() => fetch()}
                >
                    <ReloadOutlined />刷新
                </Button>
            </div>
            <Table
                rowKey={(data) => data.noticeid}
                dataSource={dataSource}
                columns={columns}
                size='small'
                bordered
                pagination={pagination}
                onChange={handleTableChange}
            />
            <EditModal
                form={form}
                visible={visible}
                detail={detail}
                setVisible={setVisible}
                onSubmit={() => {
                    setVisible(false);
                    fetch();
                }}
            />
            <DetailModal
                form={form}
                visible={detailModalVisible}
                detail={detail}
                setVisible={setDetailModalVisible}
            />
        </div>
    );
};

const EditModal = (props) => {
    const {visible = false, setVisible, detail = {}, form, onSubmit} = props;
    const [fileList, setFileList] = useState([]);

    useEffect(() => {
        if (visible) {
            if (detail.noticeid) {
                form.setFieldsValue({
                    headline: detail.headline,
                    noticecontent: detail.noticecontent,
                });
                let list = [];
                const setImgPush = (img, list, name) => {
                    const imgList = img.split(',');
                    imgList.forEach((item, index) => {
                        list.push({
                            uid: name + index,
                            name: name + index,
                            file_name: item,
                            status: 'done',
                            url: item,
                            file_path: item
                        });
                    });
                };
                if (detail.printurl) {
                    setImgPush(detail.printurl, list, 'printurl');
                }
                setFileList(list);
            }
        } else {
            form.resetFields();
            setFileList([]);
        }
    }, [visible]);

    const handleGetPictureWall = (file, fileList) => {
        // 获取上传的图片的相关信息
        setFileList(fileList);
    };

    

    const onFinish = async (value) => {
        let text = '添加';
        let url = mUrl.addMessNotice;
        if (detail.noticeid) {
            text = '编辑';
            value.noticeid = detail.noticeid;
            url = mUrl.updateMessNotice;
        }
        if (fileList.length) {
            value.printurl = utils.setImageUrl(fileList);
        } else {
            value.printurl = '';
        }
        const res = await post(url, value);
        if (res.state === 1) {
            message.success(text + '成功');
            onSubmit();
        }
    };

    return (
        <Modal
            getContainer={false}
            title={detail.noticeid ? '修改公告' : '新增公告'}
            visible={visible}
            onCancel={_ => setVisible(false)}
            footer={null}
        >
            <Form form={form} onFinish={onFinish}>
                <Form.Item name={"headline"}
                           label={'标题'}
                           labelCol={{span: 3}}
                           rules={[{required: true, message: '请输入标题'}]}
                           style={{marginBottom: 15}}>
                    <Input style={{width: 150}} placeholder={'请输入标题'}/>
                </Form.Item>
                <Form.Item name={"noticecontent"}
                           label={'详情'}
                           labelCol={{span: 3}}
                           rules={[{required: true, message: '请输入详情'}]}
                           style={{marginBottom: 15}}>
                    <Input.TextArea rows={5} placeholder={'请输入'}/>
                </Form.Item>
                <Form.Item
                    label='图片'
                    labelCol={{span: 3}}
                >
                    <PicturesWall
                        size={5}
                        fileList={fileList}
                        multiple={false}
                        fileUpdate={handleGetPictureWall}
                    />
                    <span style={{color: 'red'}}>最多可上传5个，建议尺寸：500*250px</span>
                </Form.Item>

                <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                    <Button
                        htmlType="submit" type={'primary'}
                    >发布</Button>
                    <Button style={{marginLeft: 15}}
                            onClick={_ => setVisible(false)}
                    >取消</Button>
                </Form.Item>
            </Form>
        </Modal>
    );
};

const DetailModal = (props) => {
    const {visible = false, setVisible, detail = {}} = props;
    const [fileList, setFileList] = useState([]);

    useEffect(() => {
        if (visible) {
            let list = [];
            const setImgPush = (img, list, name) => {
                const imgList = img.split(',');
                imgList.forEach((item, index) => {
                    list.push({
                        uid: name + index,
                        name: name + index,
                        file_name: item,
                        status: 'done',
                        url: item,
                        file_path: item
                    });
                });
            };
            if (detail.printurl) {
                setImgPush(detail.printurl, list, 'printurl');
            }
            setFileList(list);
        }
    }, [visible]);

    return (
        <Modal
            title={'详情'}
            visible={visible}
            onCancel={_ => setVisible(false)}
            footer={null}
        >
            <Form>
                <Form.Item
                    label={'标题'}
                    labelCol={{span: 3}}
                    style={{marginBottom: 15}}>
                    {detail.headline}
                </Form.Item>
                <Form.Item
                    label={'详情'}
                    labelCol={{span: 3}}
                    style={{marginBottom: 15}}>
                    {detail.noticecontent}
                </Form.Item>
                <Form.Item
                    label='图片'
                    labelCol={{span: 3}}
                >
                    <PicturesWall
                        size={fileList.length}
                        fileList={fileList}
                        multiple={false}
                        fileUpdate={() => {
                        }}
                    />
                    <span style={{color: 'red'}}>最多可上传5个，建议尺寸：500*250px</span>
                </Form.Item>
                <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                    <Button
                        onClick={_ => setVisible(false)}
                    >关闭</Button>
                </Form.Item>
            </Form>
        </Modal>
    );
};
export default connect()(Page);